<template>
  <div>
    <i-row style="height: 50px;">
      <i-col span="20">
        班级条件：
        <i-select style="width: 100px;" v-model="searchWeek" @on-change="search">
          <i-option v-for="week in weeks" :value="week.value" :key="week.value">{{week.label}}</i-option>
        </i-select>
        <i-input-number :max="255" :min="0" v-model="searchNum" @on-change="search"></i-input-number>
      </i-col>
      <i-col span="4">
        <i-button type="primary" icon="ios-arrow-back" style="width:50px;" @click="backwardShift"></i-button>
        <span>{{currentString}}</span>
        <i-button type="primary" icon="ios-arrow-forward" style="width:50px;" @click="forwardShift"></i-button>
      </i-col>
    </i-row>
    <i-row>
      <i-col span="24">
        <i-table border height="600" :columns="columns" :data="viewData.workList"></i-table>
      </i-col>
    </i-row>
    <i-upload ref="uploader" :show-upload-list="false" :action="host" :data="uploadData" :format="['jpg','jpeg','png']" :max-size="102400" :on-format-error="handleFormatError" :on-exceeded-size="handleMaxSize" :before-upload="handleBeforeUpload" :on-success="handleSuccess" :on-error="handleError" style="display:none;">
    </i-upload>
  </div>
</template>

<script>
import common from "@/common";

export default {
  name: "work-management",
  data: function() {
    return {
      searchWeek: 0,
      searchNum: 1,
      shift: 0,
      weeks: [
        {
          value: 0,
          label: "周日班"
        },
        {
          value: 1,
          label: "周一班"
        },
        {
          value: 2,
          label: "周二班"
        },
        {
          value: 3,
          label: "周三班"
        },
        {
          value: 4,
          label: "周四班"
        },
        {
          value: 5,
          label: "周五班"
        },
        {
          value: 6,
          label: "周六班"
        }
      ],
      columns: [
        {
          title: "学号",
          ellipsis: true,
          render: (h, params) => {
            return h("span", params.row.studentInfo.code);
          }
        },
        {
          title: "姓名",
          ellipsis: true,
          render: (h, params) => {
            return h("span", params.row.studentInfo.name);
          }
        }
      ],
      viewData: [],
      host: "",
      workPath: "",
      token: {},
      uploadData: {
        key: "",
        policy: "",
        OSSAccessKeyId: "",
        success_action_status: "200",
        signature: "",
        callback: "",
        "x:student_id": "",
        "x:course_date": ""
      }
    };
  },
  created() {
    const sw = common.getQueryString("sw");
    const sn = common.getQueryString("sn");
    const shift = common.getQueryString("shift");

    if (sw) {
      this.searchWeek = parseInt(sw);
    }
    if (sn) {
      this.searchNum = sn;
    }
    if (shift) {
      this.shift = parseInt(shift);
    }

    this.axios.get("/oss/basic").then(response => {
      if (response.code === 0) {
        this.host = response.data.host;
        this.workPath = response.data.workPath;
        this.uploadData.OSSAccessKeyId = response.data.accessId;
        this.uploadData.callback = response.data.callback;

        this.search();
      } else {
        this.$Message.error("获取存储主机基本信息失败。" + response.message);
      }
    });
  },
  computed: {
    current() {
      const current = new Date();
      // 移动当前日期到未来最近的一个和检索星期匹配的日期
      if (this.searchWeek >= current.getDay()) {
        current.setDate(
          current.getDate() + (this.searchWeek - current.getDay())
        );
      } else {
        current.setDate(
          current.getDate() + (7 + (this.searchWeek - current.getDay()))
        );
      }
      current.setDate(current.getDate() + 7 * this.shift);
      return current;
    },
    currentString() {
      return common.formatTitle(this.current);
    }
  },
  methods: {
    search() {
      // 清除上次动态添加的列
      this.columns.splice(2, this.columns.length - 2);

      // 清除上次残留的上传列表
      this.$refs.uploader.clearFiles();

      for (let i = -7; i < 1; i++) {
        const current = new Date(this.current);
        // 移动当前日期到过去的7周~未来1周
        current.setDate(current.getDate() + i * 7);

        this.columns[this.columns.length] = {
          title: common.formatTitle(current),
          align: "center",
          width: 100,
          render: (h, params) => {
            let workInfo;
            for (let index in params.row.workInfo) {
              if (
                common.isSameDay(
                  new Date(params.row.workInfo[index].courseDate),
                  current
                )
              ) {
                workInfo = params.row.workInfo[index];
                break;
              }
            }

            const studentInfo = params.row.studentInfo;

            if (!this.isHoliday(current)) {
              if (!workInfo) {
                return h("div", {}, [
                  h("Icon", {
                    props: {
                      type: "camera",
                      size: 40
                    },
                    nativeOn: {
                      click: () => {
                        this.clickUpload(
                          studentInfo.id,
                          common.formatStandardDate(current, "-")
                        );
                      }
                    }
                  })
                ]);
              } else {
                return h(
                  "div",
                  {
                    class: "upload-list"
                  },
                  [
                    h("img", {
                      class: {
                        "work-thumbnail": true,
                        wide: workInfo.width >= workInfo.height,
                        tall: workInfo.width < workInfo.height
                      },
                      attrs: {
                        src:
                          this.host +
                          "/" +
                          workInfo.object +
                          "?x-oss-process=style/thumbnail"
                      }
                    }),
                    h(
                      "div",
                      {
                        class: "upload-list-cover"
                      },
                      [
                        h("Icon", {
                          props: {
                            type: "ios-eye-outline",
                            size: 30
                          },
                          nativeOn: {
                            click: () => {
                              this.handleView(studentInfo, current);
                            }
                          }
                        }),
                        h("Icon", {
                          props: {
                            type: "ios-trash-outline",
                            size: 30
                          },
                          nativeOn: {
                            click: () => {
                              this.handleRemove(workInfo, studentInfo);
                            }
                          }
                        })
                      ]
                    )
                  ]
                );
              }
            } else {
              return "";
            }
          }
        };
      }

      this.axios
        .get(
          "/works/week/" +
            this.searchWeek +
            "/num/" +
            this.searchNum +
            "?shift=" +
            this.shift
        )
        .then(response => {
          if (response.code === 0) {
            this.viewData = response.data;
          } else {
            this.$Message.error("获取作品信息失败。" + response.message);
          }
        });
    },
    backwardShift() {
      this.shift--;
      this.search();
    },
    forwardShift() {
      this.shift++;
      this.search();
    },
    clickUpload(studentId, courseDate) {
      // 更新学生ID和课程日期
      this.uploadData["x:student_id"] = studentId;
      this.uploadData["x:course_date"] = courseDate;

      this.$refs.uploader.handleClick();
    },
    handleBeforeUpload(file) {
      const studentId = this.uploadData["x:student_id"];
      const courseDate = this.uploadData["x:course_date"];
      const ext = file.name.substring(file.name.lastIndexOf("."));
      const time = new Date().getTime();
      // 更新上传路径
      this.uploadData.key =
        this.workPath +
        studentId +
        "/" +
        common.formatStandardDate(new Date(courseDate)) +
        "_" +
        time +
        ext;

      return new Promise((resolve, reject) => {
        const now = new Date().getTime() / 1000;

        if (!this.token.expire || this.token.expire < now + 3) {
          // 令牌过期后重新异步取得（+3秒缓冲）
          this.axios.get("/oss/token").then(response => {
            if (response.code === 0) {
              this.token = response.data;

              // 更新安全令牌相关字段
              this.uploadData.policy = this.token.policy;
              this.uploadData.signature = this.token.signature;

              return resolve();
            } else {
              this.$Message.error("获取安全令牌失败。" + response.message);
              return reject();
            }
          });
        } else {
          // 令牌未过期时使用旧Token信息直接上传
          return resolve();
        }
      });
    },
    handleSuccess(response) {
      if (response.code === 0) {
        this.$Message.success("上传作品成功。");
        this.search();
      } else {
        this.$Message.error("上传作品失败。");
      }
    },
    handleError(error) {
      this.$Message.error("上传作品失败。" + error);
    },
    handleFormatError() {
      this.$Message.error("作品只能接受:jpg, jpeg, png格式的文件。");
    },
    handleMaxSize() {
      this.$Message.error("作品不能超过100MB。");
    },
    handleView(studentInfo, currentDate) {
      this.$router.push(
        "/home/preview?week=" +
          this.searchWeek +
          "&num=" +
          this.searchNum +
          "&shift=" +
          this.shift +
          "&sid=" +
          studentInfo.id +
          "&cd=" +
          common.formatStandardDate(currentDate, "-")
      );
    },
    handleRemove(work, student) {
      this.$Modal.confirm({
        title: "确认删除作品",
        content:
          "确认要删除学生[" +
          student.name +
          "]在[" +
          work.courseDate +
          "]课程的作品吗？",
        loading: true,
        onOk: () => {
          this.$Modal.remove();
          this.axios.delete("/works/" + work.id).then(response => {
            if (response.code === 0) {
              this.$Message.success("删除作品成功。");
              this.search();
            } else {
              this.$Message.error("删除作品失败。" + response.message);
            }
          });
        }
      });
    },
    isHoliday(day) {
      let found = false;
      for (let index in this.viewData.holidayInfo) {
        if (
          common.isSameDay(
            new Date(this.viewData.holidayInfo[index].holiday),
            day
          )
        ) {
          found = true;
          break;
        }
      }
      return found;
    }
  }
};
</script>

<style>
/*TODO: How to change to scoped*/
.ivu-table td.holiday-column {
  background-color: #bbbec4;
}

.ivu-table .remain-class-hour-prompt {
  color: #fff;
  background-color: #ff9900;
}

.ivu-table .remain-class-hour-leak {
  color: #fff;
  background-color: #ed3f14;
}

.upload-list {
  display: inline-block;
  width: 70px;
  height: 70px;
  text-align: center;
  line-height: 70px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
}

.upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}

.upload-list:hover .upload-list-cover {
  display: block;
}

.upload-list-cover i {
  color: #fff;
  font-size: 30px;
  cursor: pointer;
  margin: 0 2px;
}

div.ivu-table-cell {
  padding-left: 5px;
  padding-right: 5px;
}

.ivu-modal {
  top: 0;
}

img.wide {
  width: 68px;
}

img.tall {
  height: 68px;
}
</style>
